#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import py_compile
import sys
from subprocess import PIPE, Popen
from utils.cry import getMD5,cryptofile,zip

def genRegkey():
    home=os.path.expanduser("~")
    fpw=os.path.join(home,".password")
    seq=getSeq()
    print(f"Serial:{seq}")
    regcode=getMD5(seq+"GsH8485687")
    with open(fpw,'w') as fw:
        fw.write(regcode)
        
def getSeq():
    p = Popen("lshw -quiet -C system",shell=True,stdout=PIPE,stderr=PIPE)  
    out=p.stdout
    for ln in out.readlines():
        if b'serial' in ln:
            s= ln.split(b': ')[1][:-1].decode()
            return getMD5(s+"GsH8485687")
    return None

def touch_tar_dir(fn):
    if not os.path.exists(fn):
        os.mkdir(fn)

def processfile(frn,ftn,cry,compy):
    if compy:
        py_compile.compile(frn,ftn,optimize=2)
    elif cry:
        frn+='_'
        if len(sys.argv)>2:
            cryptofile(frn,ftn,sys.argv[2])
        else:
            cryptofile(frn,ftn)
    else:
        cmd=f"cp {frn} {ftn}"
        os.system(cmd)

def filecpy(frd,ftd,fl):
    files=os.listdir(frd)
    for f in files:
        if f+"\n" not in fl:continue
        fn,ext=os.path.splitext(f)
        frn=os.path.join(frd,f)
        if ext==".py":
            ftn=os.path.join(ftd,fn+".pyc")
        else:
            ftn=os.path.join(ftd,f)
        if os.path.isdir(frn):
            touch_tar_dir(ftn)
            filecpy(frn,ftn,fl)
            continue
        processfile(frn,ftn,ext==".bin",ext==".py")
def install():
    if len(sys.argv)<2:
        sys.argv.append("bikemanager")
    if len(sys.argv)<3:
        genRegkey()
    home=os.path.expanduser('~')
    target_dir=os.path.join(home,sys.argv[1])
    touch_tar_dir(target_dir)
    with open("installfiles","r") as fr:
        filelist=fr.readlines()
    filecpy("./",target_dir,filelist)
    return target_dir

if __name__ == "__main__":
    install()
